package com.haitonghop.modules.girl;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.haitonghop.R;
import com.haitonghop.controls.AdsViewControl;
import com.haitonghop.controls.DataCachedControl;
import com.haitonghop.data.TamDiemDetailModuleData;
import com.haitonghop.main.AdsBussiness;
import com.haitonghop.modules.tamdiem.TamDiemDetailModulesRenderAdapter;
import com.haitonghop.network.APIRequestWorker;
import com.haitonghop.network.Request;
import com.haitonghop.network.RequestListener;
import com.haitonghop.requester.GirlRequester;
import com.haitonghop.utils.AppSettingParams;
import com.haitonghop.utils.Logger;

public class GirlCollectionActivity extends Activity implements OnScrollListener, RequestListener, OnItemClickListener {

	LinearLayout loadingPage = null;
	LinearLayout loadingError = null;

	LinearLayout mainContent = null;
	AdsViewControl prviewTamDiem = null;
	LinearLayout loadingMore = null;
	GridView imageListView = null;

	TamDiemDetailModulesRenderAdapter tamDiemRenderAdapter = null;
	String idModules = "";
	String nameTitle = "";
	boolean isLoading = false;

	long requestId = -1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.tamdiem_detail_module_activity_layout);
		init();

		loadingPage = (LinearLayout) findViewById(R.id.loadingpagetamdiem);
		loadingError = (LinearLayout) findViewById(R.id.loadingError);
		loadingMore = (LinearLayout) findViewById(R.id.loadMore);
		loadingError.setVisibility(View.INVISIBLE);

		TextView moduleName = (TextView) findViewById(R.id.moduleName);
		moduleName.setText("Hàng tuyển ");

		mainContent = (LinearLayout) findViewById(R.id.mainContent);

		prviewTamDiem = (AdsViewControl) findViewById(R.id.prviewTamDiem);
		imageListView = (GridView) findViewById(R.id.imageListView);

		TextView textView = (TextView) findViewById(R.id.titleActivity);
		textView.setText(nameTitle);

		// Button button = (Button) findViewById(R.id.btnMoreFunctions);
		// button.setBackgroundResource(R.drawable.refresh_indicator);
		// button.setOnClickListener(new OnClickListener() {
		//
		// public void onClick(View v) {
		// runOnUiThread(new Runnable() {
		// public void run() {
		// if (!isLoading) {
		// // tamDiemRenderAdapter.clearData();
		//
		// isLoading = true;
		//
		// imageListView.setVisibility(View.INVISIBLE);
		// loadingError.setVisibility(View.GONE);
		// loadingPage.setVisibility(View.VISIBLE);
		//
		// TamDiemRequester requester =
		// TamDiemRequester.getDetailModules(idModules, page,
		// TamDiemDetailModulesActivity.this);
		// requestId = AppSettingParams.nextRequestId();
		// requester.setRequestId(requestId);
		// APIRequestWorker.getInstance().addAPIRequest(requester);
		// }
		// }
		// });
		// }
		// });

		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					requestId = -1;
					DataCachedControl.getInstance().clearCached(DataCachedControl.TAM_DIEM__DETAIL_TOPIC_LIST);
					finish();
				}
			});
		}
	}

	void doAdsByServer() {
		AdsBussiness.getInstance().doGetAdsFromServer(this, prviewTamDiem);
	}

	@Override
	protected void onDestroy() {
		APIRequestWorker.getInstance().clearAllRequests();
		DataCachedControl.getInstance().clearCached(DataCachedControl.TAM_DIEM__DETAIL_TOPIC_LIST);
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			requestId = -1;
			DataCachedControl.getInstance().clearCached(DataCachedControl.TAM_DIEM__DETAIL_TOPIC_LIST);
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		onStartUp();
	}

	int page = 1;

	private void onStartUp() {

		loadingPage.setVisibility(View.VISIBLE);

		loadingError.setVisibility(View.INVISIBLE);
		loadingMore.setVisibility(View.INVISIBLE);
		loadingError.setVisibility(View.INVISIBLE);
		mainContent.setVisibility(View.INVISIBLE);
		prviewTamDiem.setVisibility(View.INVISIBLE);
		imageListView.setVisibility(View.INVISIBLE);

		ArrayList<TamDiemDetailModuleData> cachedList = (ArrayList<TamDiemDetailModuleData>) DataCachedControl.getInstance().getCached(DataCachedControl.TAM_DIEM__DETAIL_TOPIC_LIST);
		if (cachedList != null && !cachedList.isEmpty()) {
			fillDatatoGridView(cachedList);
		} else {
			Request requester = GirlRequester.getGirlCollection(page, 50, this);
			requestId = AppSettingParams.nextRequestId();
			requester.setRequestId(requestId);
			APIRequestWorker.getInstance().addAPIRequest(requester);
		}
	}

	void init() {
	}

	void fillDatatoGridView(final ArrayList<TamDiemDetailModuleData> requestedDataList) {

		if (imageListView != null) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					DataCachedControl.getInstance().putCached(DataCachedControl.TAM_DIEM__DETAIL_TOPIC_LIST, requestedDataList);
					if (tamDiemRenderAdapter == null) {
						tamDiemRenderAdapter = new TamDiemDetailModulesRenderAdapter(GirlCollectionActivity.this, 1, 1, requestedDataList);
						imageListView.setAdapter(tamDiemRenderAdapter);
					} else {
						tamDiemRenderAdapter.setBlockList(requestedDataList);
						tamDiemRenderAdapter.notifyDataSetChanged();
					}

					imageListView.setOnItemClickListener(GirlCollectionActivity.this);
					imageListView.setOnScrollListener(GirlCollectionActivity.this);

					loadingPage.setVisibility(View.GONE);
					loadingError.setVisibility(View.GONE);
					loadingMore.setVisibility(View.GONE);

					mainContent.setVisibility(View.VISIBLE);
					prviewTamDiem.setVisibility(View.VISIBLE);
					imageListView.setVisibility(View.VISIBLE);

					isLoading = false;

					doAdsByServer();
				}
			});

		}
	}

	ArrayList<TamDiemDetailModuleData> requestedDataList;

	@Override
	public void onRequestComplete(final Request request) {
		Logger.logMe("requestId = " + requestId);
		if (request instanceof GirlRequester) {
			Logger.logMe("requestId >>>> " + requestId);
			requestedDataList = ((GirlRequester) request).getTamDiemDetailModuleDataDatas();
			Logger.logMe("requestId >>>" + requestedDataList.size());
			fillDatatoGridView(requestedDataList);
		}
	}

	@Override
	public void onRequestFailed(String errorMsg, Request request) {
		if (requestId == request.getRequestId()) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					loadingPage.setVisibility(View.GONE);
					loadingError.setVisibility(View.VISIBLE);
					loadingMore.setVisibility(View.GONE);

					mainContent.setVisibility(View.GONE);
					prviewTamDiem.setVisibility(View.GONE);
					imageListView.setVisibility(View.GONE);

					isLoading = false;

					doAdsByServer();
				}
			});
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
		Logger.logMe("1");
		if (tamDiemRenderAdapter != null) {
			Logger.logMe("2");
			TamDiemDetailModuleData diemMetalData = tamDiemRenderAdapter.getItem(index);
			final String href = diemMetalData.getHref();
			if (href != null && !"".equals(href)) {
				Intent intent = new Intent(getApplication(), GirlCollectionDetailAlbumActivity.class);
				intent.putExtra("href", href);
				intent.putExtra("NAME", diemMetalData.getTitle());

				startActivity(intent);
			}
		}

	}

	RequestListener listenerLoadMore = new RequestListener() {

		@Override
		public void onRequestFailed(String errorMsg, Request request) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (loadingMore != null && loadingMore.getVisibility() != View.GONE)
						loadingMore.setVisibility(View.GONE);
				}
			});

		}

		@Override
		public void onRequestComplete(Request request) {
			if (request instanceof GirlRequester) {
				ArrayList<TamDiemDetailModuleData> newData = ((GirlRequester) request).getTamDiemDetailModuleDataDatas();

				for (TamDiemDetailModuleData tamDiemDetailModuleData : newData) {
					requestedDataList.add(tamDiemDetailModuleData);
				}

				fillDatatoGridView(requestedDataList);
				isLoading = newData.isEmpty();
				if(newData.isEmpty()) stop = true;
Log.i("fillDatatoGridView", ">>>>>>>>>>"+isLoading);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if (loadingMore != null && loadingMore.getVisibility() != View.GONE)
							loadingMore.setVisibility(View.GONE);
					}
				});
			}

		}
	};
	boolean stop = false;
	@Override
	public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if(stop) return;
		int lastInScreen = firstVisibleItem + visibleItemCount;
		if (!isLoading && tamDiemRenderAdapter != null && !tamDiemRenderAdapter.isEmpty() && (lastInScreen == totalItemCount) && (page < 100)) {
			if (loadingMore != null && loadingMore.getVisibility() != View.VISIBLE)
				loadingMore.setVisibility(View.VISIBLE);
			isLoading = true;
			page += 1;
			Log.i("fillDatatoGridView", ">>>>>>>>>>"+isLoading);

			Request requester = GirlRequester.getGirlCollection(page, 50, listenerLoadMore);
			APIRequestWorker.getInstance().addAPIRequest(requester);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}
}
